﻿using System;
using System.Collections.Generic;
using System.Web;
using StockTrader.BusinessService.DataContract.HnxInfo;
using System.Timers;
using StockTrader.QuoteCenter.Streamer.DAL;

namespace StockTrader.QuoteCenter.Streamer.BLL
{
    public static class DataAdapter
    {
        public static List<HnxOrdersData> orders = new List<HnxOrdersData>();
        public static List<HnxStockData> stocks = new List<HnxStockData>();
        public static List<HnxMarketData> markets = new List<HnxMarketData>();
        public static List<HnxTopPriceData> topprices = new List<HnxTopPriceData>();
        static DALclient client = new DALclient();

        public static string lastOrderTime = " ";
        public static string lastDealTime = " ";
        public static bool Initialized { get; private set; }

        public delegate void StocksChangedDeleaget(StocksEventArgs args);
        public static event StocksChangedDeleaget OnStocksChanged;

        private static Timer oStocksTimer;

        static DataAdapter()
        {
            Initialized = true;

            //Start a timer that simulate a change to the stocks
            oStocksTimer = new Timer();
            oStocksTimer.Interval = 500;
            oStocksTimer.Elapsed += new ElapsedEventHandler(StocksTimer_Elapsed);
            oStocksTimer.Enabled = true;
            oStocksTimer.Start();
        }

        private static void StocksTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            //Stop the timer and update the stocks
            oStocksTimer.Stop();

            List<HnxStockData> srcStockInfo = client.getOHnxAllStockInfo();
            List<HnxStockData> newStockInfo = new List<HnxStockData>();

            foreach (HnxStockData stock in srcStockInfo)
                if (!stocks.Contains(stock))
                {
                    newStockInfo.Add(stock);
                    stocks.Add(stock);
                }

            oStocksTimer.Start();

            if ((OnStocksChanged != null) && (newStockInfo.Count > 0))
            {
                OnStocksChanged(new StocksEventArgs(newStockInfo));
            }
        }
    }

    public class StocksEventArgs : EventArgs
    {
        public List<HnxStockData> stock = new List<HnxStockData>();
        public StocksEventArgs(List<HnxStockData> newdata)
        {
            stock.AddRange(newdata);
        }

    }
}
